from selenium import webdriver
# from selenium.common import TimeoutException
from selenium.webdriver.common.by import By
# from selenium.webdriver.common.devtools.v85.debugger import step_out
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
import time
import sys
import threading

# from yijiaoyanTest.multi_chrome import thread

timeunit = 6000
timestamp = 0
timestamp2 = 0
timestamp3 = 0
timestamp4 = 0
# url = "https://teaching-research.cszhxy.com/?access_token="
url = "https://teaching-research-demo.cszhxy.com/?access_token="
js_code = """
    document.addEventListener('click', function(event) {
        let indicator = document.createElement('div');
        indicator.style.position = 'absolute';
        indicator.style.width = '10px';
        indicator.style.height = '10px';
        indicator.style.backgroundColor = 'red';
        indicator.style.borderRadius = '50%';
        indicator.style.zIndex = '10000';
        indicator.style.left = event.pageX + 'px';
        indicator.style.top = event.pageY + 'px';
        document.body.appendChild(indicator);

        // 设置一个定时器，让指示器在几秒后消失
        setTimeout(() => indicator.remove(), 20000);
    });
"""


def login_jiaoyuyun(driver, username, password):
    # //*[@id="loginfr"]/button[1]/span
    login_button = WebDriverWait(driver, timeunit).until(
        EC.element_to_be_clickable((By.XPATH, '//button[span[text()="登录"]]'))
    )
    login_button.click()
    username_input = WebDriverWait(driver, timeunit).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="loginForm"]/div[1]/input'))
    )
    username_input.click()
    username_input.send_keys(username)
    password_input = WebDriverWait(driver, timeunit).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="loginForm"]/div[2]/input'))
    )
    password_input.click()
    password_input.send_keys('Csjy8888')

    login_button = WebDriverWait(driver, timeunit).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="loginForm"]/button'))
    )
    login_button.click()


def login_yijiaoyan(driver):
    # zhihuijiaoyu_tap = WebDriverWait(driver, 20).until(
    #     EC.presence_of_element_located((By.XPATH, '//*[@id="tab-2"]'))
    # )
    # # 打印元素的文本，确保已定位到
    # print(zhihuijiaoyu_tap.text)
    # # 点击 '智慧教学类' 选项
    # zhihuijiaoyu_tap.click()
    # #
    yijiaoyan_button = WebDriverWait(driver, timeunit).until(
        EC.element_to_be_clickable((By.XPATH, '//span[text()="易教研"]'))
    )
    print(yijiaoyan_button.text)
    main_window = driver.current_window_handle
    yijiaoyan_button.click()
    all_windows = driver.window_handles

    # 切换到新窗口/标签
    if all_windows[-1] != main_window:
        driver.switch_to.window(all_windows[-1])
        driver.execute_script(js_code)


def search_jiaoyan(driver, username, timestap0):
    search_box = WebDriverWait(driver, timeunit).until(
        EC.visibility_of_element_located((By.XPATH, '//input[contains(@placeholder, "教研名称、人员、校区")]'))
    )
    # timestamp6 = time.time()
    # print(f"{username} 登录易教研耗时:", timestamp6 - timestap0)
    search_box.click()
    search_box.send_keys("技术教研")
    search_box.send_keys(Keys.RETURN)

    # 进入教研详情页
    jiaoyan_res = WebDriverWait(driver, timeunit).until(
        EC.presence_of_element_located(
            (By.XPATH, '//div[@class="eduBox"]//div[@class="showEduBox"]//div[@class="container"][1]'))
    )
    time.sleep(2)
    main_window = driver.current_window_handle
    jiaoyan_res.click()
    all_windows = driver.window_handles

    # 切换到新窗口/标签
    if all_windows[-1] != main_window:
        driver.switch_to.window(all_windows[-1])
        driver.execute_script(js_code)


def enter_jiaoyan(driver):
    jinrujiaoyan_btn = WebDriverWait(driver, timeunit).until(
        EC.presence_of_element_located((By.XPATH, '//span[@class="btn" and text()="进入教研"]'))
    )
    jinrujiaoyan_btn.click()
    fangjian_btn = WebDriverWait(driver, timeunit).until(
        EC.presence_of_element_located((By.XPATH, '//div[@class="close"]/span[@class="svg-icon"]'))
    )
    fangjian_btn.click()


def startTest2(username, password):
    # thread_id = threading.get_ident()  # 获取当前线程的 ID
    # print(f"Task {username} is running in thread ID {thread_id}")
    timestamp = time.time()
    print(f'start: {username}', timestamp)
    chrome_options = Options()

    # 添加无痕模式参数,关闭无痕模式https默认转化参数
    chrome_options.add_argument("--incognito")
    chrome_options.add_argument("--disable-features=HttpsFirstModeIncognito")
    chrome_options.add_argument("--use-fake-ui-for-media-stream")
    # 添加headless:
    # chrome_options.add_argument("--headless")  # 开启无头模式
    # chrome_options.add_argument("--no-sandbox")  # 非沙盒模式（容错设置）
    # chrome_options.add_argument("--disable-dev-shm-usage")  # 禁止共享内存（容错设置）
    # # 创建 Service 对象并设置日志级别
    # service = Service(
    #     executable_path="C:\\Users\\电脑\\.cache\\selenium\\chromedriver\\win64\\130.0.6723.91\\chromedriver.exe",
    #     # log_path="F:\\projects\\python\\pythonProject\\chromedriver.log",
    #     log_output=f"F:\\projects\\python\\pythonProject\\{username}chromedriver.log")
    # service.creationflags = "--verbose"  # 设置详细的日志级别
    # service.start()
    # 启动浏览器
    # driver = webdriver.Chrome(options=chrome_options, service=service)
    driver = webdriver.Chrome(options=chrome_options)
    # driver.get("https://www.cszhxy.com/csindex")
    driver.get(url + password)
    # print(url)

    # try:
    # login_jiaoyuyun(driver, username, password)
    # timestamp2 = time.time()
    # print(f"{username} 登录云平台耗时:", timestamp2 - timestamp)
    # login_yijiaoyan(driver)
    # timestamp3 = time.time()
    # print(f"{username} 云平台跳转到易教研loading页面耗时:", timestamp3 - timestamp2)
    driver.execute_script(js_code)
    # try:
    search_jiaoyan(driver, username, timestamp)
    enter_jiaoyan(driver)
    timestamp5 = time.time()
    print(f"searchAndEnterRoom: {username}", timestamp5 - timestamp)
    # except TimeoutException:
    #     with open("temp.html", "w", encoding="utf-8") as f:
    #         f.write(driver.page_source)
    # input("按 Enter 键关闭浏览器...")
    # 关闭浏览器
    # input("按 Enter 键关闭浏览器...")
    # time.sleep(20)

    # except:
    print("except")
    print(sys.exc_info())
    # finally:
    driver.quit()
    end_time = time.time()
    print(f'end： {username}', end_time)
    print(f'during： {username}', end_time - timestamp)

    return username


if __name__ == '__main__':
    timestamp = time.time()
    print('start: %', timestamp)
    chrome_options = Options()

    # 添加无痕模式参数
    chrome_options.add_argument("--incognito")
    # chrome_options.add_argument("--disable-infobars")
    # chrome_options.add_argument("start-maximized")
    # chrome_options.add_argument("--disable-extensions")
    # chrome_options.add_argument("--disable-popup-blocking")
    # chrome_options.add_argument('--allow-running-insecure-content')
    # chrome_options.add_argument(
    #     "--unsafely-treat-insecure-origin-as-secure=http://220.163.11.78:8087/login/")  # Replace example.com with your site's domain
    chrome_options.add_argument("--disable-features=HttpsFirstModeIncognito")
    # chrome_options.add_argument("--disable-https-first-mode-incognito")
    # 启动浏览器
    driver = webdriver.Chrome(options=chrome_options)
    driver.get("https://www.cszhxy.com/csindex")

    # try:
    login_jiaoyuyun(driver, "13941640770", "geqiang860127")
    timestamp2 = time.time()
    print("1耗时:", timestamp2 - timestamp)
    login_yijiaoyan(driver)
    timestamp3 = time.time()
    print("2耗时:", timestamp3 - timestamp2)
    search_jiaoyan(driver, "13941640770", timestamp)
    timestamp4 = time.time()
    print("3耗时:", timestamp4 - timestamp3)
    enter_jiaoyan(driver)
    timestamp5 = time.time()
    print("4耗时:", timestamp5 - timestamp4)
    # except TimeoutException:
    #     with open("temp.html", "w", encoding="utf-8") as f:
    #         f.write(driver.page_source)
    #     input("按 Enter 键关闭浏览器...")
    # 关闭浏览器
    time.sleep(10)
    driver.quit()
